package zust.se.delicious.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import zust.se.delicious.dao.TagsDao;
import zust.se.delicious.domain.Tags;

public class TagsDaoImpl extends HibernateDaoSupport implements TagsDao {

	@Override
	public Tags get(Integer id) {
		return getHibernateTemplate().get(Tags.class, id);
	}

	@Override
	public Integer save(Tags Tags) {
		return (Integer) getHibernateTemplate().save(Tags);
	}

	@Override
	public void update(Tags Tags) {
		getHibernateTemplate().update(Tags);

	}

	@Override
	public void delete(Tags Tags) {
		getHibernateTemplate().delete(Tags);

	}

	@Override
	public void delete(Integer id) {
		getHibernateTemplate().delete(get(id));

	}

	@Override
	public List<Tags> findAll() {
		return (List<Tags>) getHibernateTemplate().find("from Tags");
	}

	@Override
	public List<Tags> findTagsByKeyword(final String keyword) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				String hql = "select tag from Bookmark bm inner join bm.tagsSet tag where bm in" +
						" (select newbm from Bookmark newbm inner join newbm.tagsSet newtag where newtag.tags_name=:keyword)";
				Query query = session.createQuery(hql).setString("keyword", keyword).setMaxResults(10);
				return query.list();
			}

		});
	}

	@Override
	public Tags get(String name) {
		List<Tags> tagList = (List<Tags>) getHibernateTemplate().find("from Tags where tags_name=?", name);
		if (tagList.size() == 1)
			return tagList.get(0);
		else if (tagList.size() == 0)
			return null;
		else
			return null;
	}

	@Override
	public List<Tags> findTagsByUrl(final String url) {
		return getHibernateTemplate().executeFind(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session) throws HibernateException, SQLException {
				String hql = "select tag from Bookmark bm inner join bm.tagsSet tag where bm in" +
						" (from Bookmark where url=:url)";
				Query query = session.createQuery(hql).setString("url", url).setMaxResults(10);
				return query.list();
			}

		});
	}

}
